const jwt = require('jsonwebtoken');
const config = require('../config')

module.exports = (req,res,next) => {
    let token = req.header('authorization')
    if(!token){
        return res.status(200).json({
            code: 400,
            msg: "Unauthorization 无token"
        })
    }
    let spaceIndex = token.indexOf(' ')

    token = token.substring(spaceIndex + 1,token.length)

    if(!token){
        return res.status(200).json({
            code: 400,
            msg: "Unauthorization 无token"
        })
    }
    try{
        //登录成功将用户数据挂载到req对象上
        const userData = jwt.verify(token,config.secret)
        req.userData = userData
    } catch(err) {
        return res.status(200).json({
            code: 401,
            msg: "Unauthorization Token无效"
        })
    }
    next()
}